package com.yunkeji.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.lock.annotation.Lock4j;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yunkeji.common.constant.CacheConstants;
import com.yunkeji.common.core.domain.PageQuery;
import com.yunkeji.common.core.domain.dto.PayLogDTO;
import com.yunkeji.common.core.page.TableDataInfo;
import com.yunkeji.common.enums.app.*;
import com.yunkeji.common.exception.ServiceException;
import com.yunkeji.common.utils.ServletUtils;
import com.yunkeji.common.utils.piggy.PiggyUtils;
import com.yunkeji.dao.domain.AppUser;
import com.yunkeji.dao.domain.PayWithDraw;
import com.yunkeji.dao.domain.PayWithDrawSign;
import com.yunkeji.dao.mapper.*;
import com.yunkeji.dao.vo.PayWithdrawVo;
import com.yunkeji.system.domain.bo.PayWithdrawBo;
import com.yunkeji.system.domain.bo.PayWithdrawCheckBo;
import com.yunkeji.system.domain.dto.WithDrawDTO;
import com.yunkeji.system.service.IPayWithdrawService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 支付-提现Service业务层处理
 *
 * @author zhang
 * @date 2024-07-10
 */
@RequiredArgsConstructor
@Service
public class PayWithdrawServiceImpl implements IPayWithdrawService {

    private final PayWithDrawMapper baseMapper;
    private final AppUserMapper appUserMapper;
    private final PayLogMapper payLogMapper;
    private final AppUserExtMapper appUserExtMapper;

    private final PayWithDrawSignMapper payWithDrawSignMapper;

    /** 查询支付-提现 */
    @Override
    public PayWithdrawVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /** 查询支付-提现列表 */
    @Override
    public TableDataInfo<PayWithdrawVo> queryPageList(PayWithdrawBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<PayWithDraw> lqw = buildQueryWrapper(bo);
//        Page<PayWithdrawVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        Page<PayWithdrawVo> result = baseMapper.selectListPage(
            bo.getPlatformId(),
            bo.getStatus(),
            bo.getPayType(),
            bo.getPayStatus(),
            bo.getWithdrawDateBefore(),
            bo.getWithdrawDateAfter(),
            bo.getCheckDateBefore(),
            bo.getCheckDateAfter(),
            pageQuery.build());
        return TableDataInfo.build(result);
    }

    /** 查询支付-提现列表 */
    @Override
    public List<PayWithdrawVo> queryList(PayWithdrawBo bo) {
        LambdaQueryWrapper<PayWithDraw> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<PayWithDraw> buildQueryWrapper(PayWithdrawBo bo) {
        LambdaQueryWrapper<PayWithDraw> lqw = Wrappers.lambdaQuery();
        lqw.between(
                bo.getWithdrawDateAfter() != null && bo.getWithdrawDateBefore() != null,
                PayWithDraw::getCreateTime,
                bo.getWithdrawDateBefore(),
                bo.getWithdrawDateAfter());
        lqw.between(
                bo.getCheckDateAfter() != null && bo.getCheckDateBefore() != null,
                PayWithDraw::getCheckTime,
                bo.getCheckDateBefore(),
                bo.getCheckDateAfter());
        lqw.eq(bo.getPhone() != null, PayWithDraw::getPhone, bo.getPhone());
        lqw.eq(bo.getPlatformId() != null, PayWithDraw::getPlatformId, bo.getPlatformId());
        lqw.eq(bo.getStatus() != null, PayWithDraw::getCheckStatus, bo.getStatus());
        lqw.eq(bo.getPayType() != null, PayWithDraw::getPayType, bo.getPayType());
        lqw.eq(bo.getPayStatus() != null, PayWithDraw::getPayStatus, bo.getPayStatus());
        lqw.orderByDesc(PayWithDraw::getCreateTime);
        return lqw;
    }

    /** 新增支付-提现 */
    @Override
    public Boolean insertByBo(PayWithdrawBo bo) {
        PayWithDraw add = BeanUtil.toBean(bo, PayWithDraw.class);
        add.setBranch(Integer.valueOf(ServletUtils.getRequest().getHeader("branch")));
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            //  bo.setId(add.getId());
        }
        return flag;
    }

    /** 修改支付-提现 */
    @Override
    public Boolean updateByBo(PayWithdrawBo bo) {
        PayWithDraw update = BeanUtil.toBean(bo, PayWithDraw.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /** 保存前的数据校验 */
    private void validEntityBeforeSave(PayWithDraw entity) {
        // TODO 做一些数据校验,如唯一约束
    }

    /** 批量删除支付-提现 */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            // TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    @Lock4j(
            name = CacheConstants.LOCK_WITHDRAW_LOCK,
            keys = {"#bo.id"})
    public void pass(PayWithdrawCheckBo bo) {
        WithDrawDTO withDrawDTO = checkStatus(bo);
        PayWithDrawSign payWithDrawSign = withDrawDTO.getPayWithDrawSign();
        PayWithDraw payWithDraw = withDrawDTO.getPayWithDraw();
        String outerTradeNo =
                PiggyUtils.singleSubmit(
                        payWithDrawSign.getUserName(),
                        payWithDrawSign.getMobile(),
                        payWithDrawSign.getIdCardNo(),
                        SettleTypeEnums.getByType(payWithDraw.getPayType()),
                        payWithDraw.getWithdrawAccount(),
                        payWithDraw.getExpectedNum());
        if (StrUtil.isNotEmpty(outerTradeNo)) {
            baseMapper.updateById(
                    PayWithDraw.builder()
                            .id(bo.getId())
                            .checkTime(new Date())
                            .outerTradeNo(outerTradeNo)
                            .payStatus(WithdrawPayStatus.等待到账.getCode())
                            .checkStatus(CheckStatus.审核通过.getCode())
                            .build());
        } else {
            baseMapper.updateById(
                    PayWithDraw.builder()
                            .id(bo.getId())
                            .checkTime(new Date())
                            .payStatus(WithdrawPayStatus.到账异常.getCode())
                            .checkStatus(CheckStatus.审核通过.getCode())
                            .build());
        }
    }

    @Override
    @Lock4j(
            name = CacheConstants.LOCK_WITHDRAW_LOCK,
            keys = {"#bo.id"})
    public void refuse(PayWithdrawCheckBo bo) {
        PayWithDraw payWithDraw1 =
                baseMapper.selectOne(
                        Wrappers.lambdaQuery(PayWithDraw.class)
                                .eq(PayWithDraw::getId, bo.getId())
                                .eq(PayWithDraw::getCheckStatus, CheckStatus.待审核.getCode()));

        if (payWithDraw1 == null) {
            throw new ServiceException("状态异常");
        }
        baseMapper.updateById(
                PayWithDraw.builder()
                        .refundFlag(EnableEnum.YES.getCode())
                        .id(bo.getId())
                        .checkTime(new Date())
                        .remark(bo.getReason())
                        .checkStatus(CheckStatus.审核拒绝.getCode())
                        .build());
        PayWithDraw payWithDraw = baseMapper.selectById(bo.getId());
        // TODO 退款
        //        AppUser appUser = appUserMapper.selectById(payWithDraw.getUserId());
        //        AppUserExt appUserExt = appUserExtMapper.selectById(payWithDraw.getUserId());
        // 金钱回滚
        appUserMapper.logAddDiamondBalance(
                PayLogDTO.builder()
                        .traceId(payWithDraw.getId())
                        .changeNum(payWithDraw.getDiamondNum())
                        .uid(payWithDraw.getUserId())
                        .serviceTag("提现审核拒绝")
                        .logType(PayLogTypeEnums.收益_提现拒绝退款)
                        .build());
    }

    private WithDrawDTO checkStatus(PayWithdrawCheckBo bo) {
        PayWithDraw payWithDraw1 =
                baseMapper.selectOne(
                        Wrappers.lambdaQuery(PayWithDraw.class)
                                .eq(PayWithDraw::getId, bo.getId())
                                .eq(PayWithDraw::getCheckStatus, CheckStatus.待审核.getCode()));

        if (payWithDraw1 == null) {
            throw new ServiceException("状态异常");
        }
        BigDecimal cashPooling = PiggyUtils.getCashPooling(payWithDraw1.getPayType());
        BigDecimal expectedNum = payWithDraw1.getExpectedNum();
        if (NumberUtil.isLess(cashPooling, expectedNum)) {
            throw new ServiceException("资金池余额不足");
        }
        PayWithDrawSign payWithDrawSign =
                payWithDrawSignMapper.selectById(payWithDraw1.getUserId());
        // 用户状态不正常时，直接拒绝该用户的提现
        AppUser appUser = appUserMapper.selectById(payWithDraw1.getUserId());
        if (Objects.isNull(appUser) || appUser.getStatus() > 0) {
            this.refuse(bo);
        }
        if (payWithDrawSign == null) {
            throw new ServiceException("该用户未电签,请先联系电签");
        }
        boolean b =
                PiggyUtils.needToSign(payWithDrawSign.getIdCardNo(), payWithDrawSign.getUserName());
        if (b) {
            throw new ServiceException("该用户电签过期,请先联系电签");
        }
        return WithDrawDTO.builder()
                .payWithDraw(payWithDraw1)
                .payWithDrawSign(payWithDrawSign)
                .build();
    }
}
